package com.fary.rabbitmq.simple;

import com.fary.rabbitmq.config.RabbitMQFactory;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {

    private static final String QUEUE = "simpleQueue";

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory factory = RabbitMQFactory.getConnectionFactory();
        // 创建连接
        Connection connection = null;
        // 创建通道
        Channel channel = null;
        try {
            // 创建连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();
            // 声明队列，消费者也需要声明队列，以防运维先启动消费者，而不是生产者。
            channel.queueDeclare(QUEUE, true, false, false, null);

            com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel) {
                //消费者收到后，做什么
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //具体的业务逻辑
                    System.out.println("consumerTag = " + consumerTag);
                    System.out.println("envelope.getDeliveryTag() = " + envelope.getDeliveryTag());
                    System.out.println("envelope.getExchange() = " + envelope.getExchange());
                    System.out.println("envelope.getRoutingKey() = " + envelope.getRoutingKey());

                    System.out.println("body = " + new String(body));
                }
            };
            // 消费者消费消息
            channel.basicConsume(QUEUE, true, consumer);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
